package ynu.edu.controller;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.dto.CartDTO;
import ynu.edu.entities.BaseResponse;
import ynu.edu.entity.CartEntity;
import ynu.edu.service.CartService;

import java.util.List;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     */
    @PostMapping
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "addToCartFallback")
    public ResponseEntity<BaseResponse<CartDTO>> addToCart(@RequestBody CartEntity cart) {
        CartDTO result = cartService.addToCart(cart);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(BaseResponse.success(result));
    }

    /**
     * 更新购物车中商品数量
     */
    @PutMapping("/{cartId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "updateCartItemQuantityFallback")
    public ResponseEntity<BaseResponse<CartDTO>> updateCartItemQuantity(
            @PathVariable Integer cartId,
            @RequestParam Integer quantity) {
        CartDTO result = cartService.updateCartItemQuantity(cartId, quantity);
        return ResponseEntity.ok(BaseResponse.success(result));
    }

    /**
     * 获取用户购物车列表
     */
    @GetMapping("/user/{userId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getCartsByUserIdFallback")
    public ResponseEntity<BaseResponse<List<CartDTO>>> getCartsByUserId(@PathVariable("userId") String userId) {
        List<CartDTO> carts = cartService.getCartsByUserId(userId);
        return ResponseEntity.ok(BaseResponse.success(carts));
    }

    /**
     * 获取用户特定商家的购物车列表
     */
    @GetMapping("/user/{userId}/merchant/{businessId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "getCartsByUserIdAndBusinessIdFallback")
    public ResponseEntity<BaseResponse<List<CartDTO>>> getCartsByUserIdAndBusinessId(
            @PathVariable("userId") String userId,
            @PathVariable("businessId") Integer businessId) {
        List<CartDTO> carts = cartService.getCartsByUserIdAndBusinessId(userId, businessId);
        return ResponseEntity.ok(BaseResponse.success(carts));
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/{cartId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "deleteCartFallback")
    public ResponseEntity<BaseResponse<Void>> deleteCart(@PathVariable("cartId") Integer cartId) {
        cartService.deleteCart(cartId);
        return ResponseEntity.ok(BaseResponse.success());
    }

    /**
     * 清空用户购物车
     */
    @DeleteMapping("/user/{userId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "clearUserCartFallback")
    public ResponseEntity<BaseResponse<Void>> clearUserCart(@PathVariable("userId") String userId) {
        cartService.clearUserCart(userId);
        return ResponseEntity.ok(BaseResponse.success());
    }

    /**
     * 清空用户特定商家的购物车
     */
    @DeleteMapping("/user/{userId}/merchant/{businessId}")
    @CircuitBreaker(name = "orderServiceBreaker", fallbackMethod = "clearUserBusinessCartFallback")
    public ResponseEntity<BaseResponse<Void>> clearUserBusinessCart(
            @PathVariable String userId,
            @PathVariable Integer businessId) {
        cartService.clearUserBusinessCart(userId, businessId);
        return ResponseEntity.ok(BaseResponse.success());
    }

    // 降级方法

    public ResponseEntity<BaseResponse<CartDTO>> addToCartFallback(CartEntity cart, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "添加商品到购物车失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<CartDTO>> updateCartItemQuantityFallback(Integer cartId, Integer quantity, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "更新购物车商品数量失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<List<CartDTO>>> getCartsByUserIdFallback(String userId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "获取购物车列表失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<List<CartDTO>>> getCartsByUserIdAndBusinessIdFallback(
            String userId, Integer businessId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "获取购物车列表失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<Void>> deleteCartFallback(Integer cartId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "删除购物车商品失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<Void>> clearUserCartFallback(String userId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "清空购物车失败，服务不可用: " + e.getMessage()));
    }

    public ResponseEntity<BaseResponse<Void>> clearUserBusinessCartFallback(
            String userId, Integer businessId, Exception e) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(BaseResponse.error(503, "清空购物车失败，服务不可用: " + e.getMessage()));
    }
} 